const mysql = require("mysql"); //引入mysql数据库

function dbCore() {
  return mysql.createConnection({
    host: "localhost",
    port: 3306,
    user: "root",
    password: "406427",
    database: "small_program",
    multipleStatements: true, // 允许同时请求多条 sql 语句
    timezone: "utc", // 解决时区时间统一的问题
  });
}
module.exports = {
  dbconfig(res, sql, arr, fun) {
    // console.log(111);
    let DB = dbCore();
    DB.connect();
    DB.query(sql, arr, function (err, data) {
      if (!err) {
        fun(data);
      } else {
        res.send({
          code: 500,
          msg: "数据库连接失败",
        });
      }
    });
    DB.end();
  },
  dbTransaction(res, sql, whereArr, fun) {
    let DB = dbCore();
    DB.connect();
    for (let i = 0; i < whereArr.length; i++) {
      DB.query(sql, whereArr[i], function (err, data) {
        if (!err) {
          fun(data);
        } else {
          res.send({
            code: 500,
            msg: "数据库连接失败",
          });
        }
      });
    }

    DB.end();
  },
};
